package edu.pku.sei.modeler.neditor.command;

import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.commands.Command;

import edu.pku.sei.modeler.model.core.MetaModelElement;
import edu.pku.sei.modeler.model.notation.core.ShapeNode;
import edu.pku.sei.modeler.model.notation.shape.Shape;
import edu.pku.sei.modeler.neditor.model.Diagram;

public class ChangeConstraintCommand extends Command {
	private MetaModelElement parent;
	private MetaModelElement child;
	private Rectangle constraint;

	public void setChild(MetaModelElement child) {
		this.child = child;
	}

	public void setConstraint(Rectangle constraint) {
		this.constraint = constraint;
	}

	public void setParent(MetaModelElement parent) {
		this.parent = parent;
	}

	@Override
	public boolean canExecute() {
		return true;
	}

	private Rectangle oldConstraint = new Rectangle();
	
	@Override
	public void execute() {
		ShapeNode s = (ShapeNode)child;
		oldConstraint.setBounds(s.getBound());
		if(parent instanceof Diagram){
			s.setBound(constraint);
		} else {
			ShapeNode p = (ShapeNode)parent;
			constraint.translate(p.getBound().x, p.getBound().y);
			((Shape)parent).changeChildBound(s, constraint);
		}
	}

	@Override
	public void redo() {
		if(parent instanceof Diagram){
			ShapeNode s = (ShapeNode)child;
			s.setBound(constraint);
		} else {
			ShapeNode s = (ShapeNode)child;
			ShapeNode p = (ShapeNode)parent;
			((Shape)parent).changeChildBound(s, constraint);
		}
	}

	@Override
	public void undo() {
		if(parent instanceof Diagram){
			ShapeNode s = (ShapeNode)child;
			s.setBound(oldConstraint);
		} else {
			ShapeNode s = (ShapeNode)child;
			ShapeNode p = (ShapeNode)parent;
			((Shape)parent).changeChildBound(s, oldConstraint);
		}
	}

}
